package com.me.test.interceptor;

import com.me.test.annotation.DataPermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据开关决定是否启用
 *
 * @author ME
 */
public class TokenInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    /**
     * prepare Handle，准备处理，顾名思义，该方法将在 Controller 之前调用，进行一些预处理，
     * 并且可以通过 返回 `false` 中断 Controller 执行。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String uri = request.getRequestURI();
        System.out.println("==> MyInterceptor preHandle - [/**] 匹配任意无后缀的目录 preHandle.  url={" + uri + "}");
        // try {
        //     response.sendRedirect("error/500.html");
        //     return false;
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        // 处理 @DataPermission 注解
        if (method.hasMethodAnnotation(DataPermission.class)) {
            DataPermission annotation = method.getMethodAnnotation(DataPermission.class);
        }

        return true;
    }

    /**
     * Controller 处理后，将 ModelAndView 返回给前端控制器之前 执行
     *
     * @param request  the request
     * @param response the response
     * @param arg2     the arg 2
     * @param mv       the mv
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView mv) {
        System.out.println("<== MyInterceptor postHandle - [/**] 匹配任意无后缀的目录  postHandle.  url={" + request.getRequestURI() + "}");
    }

    /**
     * 页面渲染完数据后，执行 afterCompletion 进行清理工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception ex) {
        System.out.println("<== MyInterceptor afterCompletion - 善后工作");
    }

}
